import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';
import { AuthService } from '../auth.servics';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { User } from './User';

function userNameValidator(control: FormControl): {[s:string]: boolean } {
  if(!control.value.match(/^admin/)) { return{invalidUser:true};}
    return{};
}


@Component({
  selector: 'app-login-component',
  templateUrl: './login-component.component.html',
  styleUrls: ['./login-component.component.css']
})
export class LoginComponentComponent implements OnInit {
  myForm: FormGroup;
  userName: FormControl;
  password: FormControl;
  baseUrl = 'http://127.0.0.1:8080/';
  users$: Observable<User[]>;
  title(title: any) {
    throw new Error('Method not implemented.');
  }

  name$: Observable<string> | undefined;

  constructor(private authService: AuthService, private fb: FormBuilder, private httpClient: HttpClient) {
    this.myForm = this.fb.group({
      'userName' :['',Validators.compose([Validators.required,Validators.minLength(5),userNameValidator])],
      'password':['',Validators.compose([Validators.required, Validators.minLength(6)])],
      // 'userName': [''],
      // 'password': [''],
    });
    this.users$ = <Observable<User[]>>this.httpClient.get(this.baseUrl + 'users');
    this.userName = <FormControl>this.myForm.controls['userName'];
    this.password = <FormControl>this.myForm.controls['password'];

    this.name$=this.userName.valueChanges;
    this.userName.valueChanges.subscribe(val =>{
      console.log(val);
    })
  }

  ngOnInit(): void {
  }

  login() {
    this.httpClient.post(this.baseUrl + 'login', this.myForm.value).subscribe(
      (val: any) => {
        if (val.succ) {
          console.log(val.succ)
          
        } else {
          alert('密码错误');
          this.authService.logout();
          window.location.href = "http://localhost:4200/login";

        }
      });
      this.authService.login();
     console.log(this.myForm.value)
  }
  onSubmit(value:any){
    console.log(value);
}

}
